﻿using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Runtime.InteropServices; 
using System.Xml; 
using System.Diagnostics; 
using System.IO;
using DevComponents.DotNetBar;
using CmTTPlayer;

namespace Mp3Play
{
   public partial class Frm : Form 
    { 
        /// 
        /// 强行释放内存资源 
        /// 
        /// 
        /// 
        /// 
        /// 
        [DllImport("kernel32", EntryPoint = "SetProcessWorkingSetSize", ExactSpelling = true, CharSet = CharSet.Ansi, SetLastError = true)] 
        public static extern int SetProcessWorkingSetSize(int hProcess, int dwMinimumWorkingSetSize, int dwMaximumWorkingSetSize); 
        private Media media = new Media(); 
        //自增长序号 
        private int number = 1; 
        //当前播放曲目Index 
        private int changeValue = 0; 
        //当前播放曲目自增长序号 
        private string changeItemText = "1"; 
        private Timer tmrShow = new Timer(); 
        Timer tmrClose; 
        private int startX, StartY; 
        public Frm() 
        { 
            InitializeComponent(); 
        } 

        /// 
        /// 初始化窗体数据 
        /// 
        /// 
        /// 
        private void Frm_Load(object sender, EventArgs e) 
        { 
            //获取进程的模块名称 
            string mName = Process.GetCurrentProcess().MainModule.ModuleName; 
            //返回没有扩展名的模块名称 
            string pName = Path.GetFileNameWithoutExtension(mName); 
            Process[] myProcess = Process.GetProcessesByName(pName); 
            if (myProcess.Length > 1) 
            { 
                MessageBox.Show("当前程序已经运行", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information); 
                this.Dispose(); 
                Application.ExitThread(); 
            } 
            else 
            { 
                this.tmrShow.Tick += new EventHandler(this.tmrShow_Tick); 
                this.tmrShow.Enabled = true; 
            }      

            //设置图标 
            this.Icon = Icon.ExtractAssociatedIcon("CmTTPlayer.ico"); 
            this.notifyIcon1.Icon = Icon.ExtractAssociatedIcon("CmTTPlayer.ico"); 
            media.SetAudioSource(Media.AudioSource.H); 
            XmlDocument xmlDoc = new XmlDocument(); 
            //获取当前应用程序路径 
            string path = Process.GetCurrentProcess().MainModule.FileName.Substring(0, Process.GetCurrentProcess().MainModule.FileName.LastIndexOf("\\")); 
            //加载Xml文件 
            xmlDoc.Load(path + "\\PlayList\\MusicFile.xml"); 
            XmlNode root = xmlDoc.SelectSingleNode("musiclist");//查找 
            XmlNodeList xnl = root.ChildNodes; 
            for (int i = 0; i < xnl.Count; i++) 
            { 
                ListViewItem item = new ListViewItem(number.ToString()); 
                item.SubItems.AddRange(new string[] { root.ChildNodes[i].Attributes["genre"].Value, root.ChildNodes[i].Attributes["lenght"].Value }); 
                item.Tag = root.ChildNodes[i].Attributes["filename"].Value; 
                lvMusicList.Items.Add(item); 
                number++; 
                Application.DoEvents(); 
            } 
            //在加载事件中执行以下 
            SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle.ToInt32(), -1, -1); 
        } 

        /// 
        /// 打开音乐文件 
        /// 
        /// 
        /// 
        private void tsmiOpenMusic_Click(object sender, EventArgs e) 
        { 
            try 
            { 
                OpenFileDialog ofd = new OpenFileDialog(); 
                ofd.Multiselect = true; 
                ofd.Filter = "音乐文件|*.mp3;*.wma;*.wav"; 
                ofd.FileName = "打开文件"; 
                if (ofd.ShowDialog() == DialogResult.OK) 
                { 
                    XmlDocument xmlDoc = new XmlDocument(); 
                    //获取当前应用程序路径 
                    string path = Process.GetCurrentProcess().MainModule.FileName.Substring(0, Process.GetCurrentProcess().MainModule.FileName.LastIndexOf("\\")); 
                    //加载Xml文件 
                    xmlDoc.Load(path + "\\PlayList\\MusicFile.xml"); 
                    XmlNode root = xmlDoc.SelectSingleNode("musiclist");//查找 
                    //遍历加载当前选中文件 
                    foreach (string fileName in ofd.FileNames) 
                    { 
                        //打开音乐设备 
                        media.OpenMusic(fileName, this.Handle); 
                        //添加ListView项 
                        ListViewItem item = new ListViewItem(number.ToString()); 
                        item.SubItems.AddRange(new string[] { Path.GetFileName(fileName),media.GetMusicLengthString() }); 
                        item.Tag = fileName; 
                        lvMusicList.Items.Add(item); 
                        XmlElement xe1 = xmlDoc.CreateElement("name");//创建一个节点 
                        xe1.SetAttribute("genre", Path.GetFileName(fileName));//设置该节点genre属性 
                        xe1.SetAttribute("filename", fileName);//设置该节点filename属性 
                        xe1.SetAttribute("lenght", media.GetMusicLengthString());//设置该节点filename属性 
                        number++; 
                        root.AppendChild(xe1);//添加到节点中                         
                        //处理消息队列 
                        Application.DoEvents(); 
                    } 
                    xmlDoc.Save(path + "\\PlayList\\MusicFile.xml"); 
                } 
                if (lvMusicList.Items.Count > 0) 
                    btnPlayOrPause.Enabled = true; 
            } 
            catch (Exception exp) 
            { 
                MessageBox.Show(exp.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Error); 
            } 

            SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle.ToInt32(), -1, -1); 
        } 

        /// 
        /// 添加本地文件夹 
        /// 
        /// 
        /// 
        string fileInfo = string.Empty; 
        private void tsmiOpenFolderMusic_Click(object sender, EventArgs e) 
        { 
            try 
            { 
                FolderBrowserDialog fbd = new FolderBrowserDialog(); 
                if (fbd.ShowDialog() == DialogResult.OK) 
                { 
                    DirectoryInfo dInfo = new DirectoryInfo(fbd.SelectedPath); 
                    //遍历该文件夹 
                    GetFolder(dInfo); 
                } 
                using (StreamWriter sw = new StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\fileInfo.txt", false, Encoding.GetEncoding("gb2312"))) 
                { 
                    sw.Write(fileInfo); 
                    sw.Flush(); 
                } 
                btnPlayOrPause.Enabled = true; 
            } 
            catch (Exception exp) 
            { 
                MessageBox.Show(exp.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Error); 
            } 
            //释放资源 
            SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle.ToInt32(), -1, -1); 
        } 

        /// 
        /// 递归文件夹 
        /// 
        /// 
        private void GetFolder(DirectoryInfo dInfo) 
        { 
            //显示其中文件 
            GetFile(dInfo); 
            //遍历文件夹中的文件夹 
            foreach (DirectoryInfo dir in dInfo.GetDirectories()) 
            { 
                //递归遍历该文件夹 
                GetFolder(dir); 
            } 
        } 

        //遍历文件夹中的文件 
        private void GetFile(DirectoryInfo dInfo) 
        { 
            XmlDocument xmlDoc = new XmlDocument(); 
            //获取当前应用程序路径 
            string path = Process.GetCurrentProcess().MainModule.FileName.Substring(0, Process.GetCurrentProcess().MainModule.FileName.LastIndexOf("\\")); 
            //加载Xml文件 
            xmlDoc.Load(path + "\\PlayList\\MusicFile.xml"); 
            XmlNode root = xmlDoc.SelectSingleNode("musiclist");//查找 
            foreach (FileInfo fileName in dInfo.GetFiles()) 
            { 
                //获取文件扩展名 
                string extension = Path.GetFileName(fileName.FullName).Substring(Path.GetFileName(fileName.FullName).IndexOf(".")); 
                //判断是否为音乐文件 
                if (extension.ToLower().Equals(".mp3") || extension.ToLower().Equals(".wma") || extension.ToLower().Equals(".wav")) 
                { 
                    media.OpenMusic(fileName.FullName, this.Handle); 
                    string[] str = new string[lvMusicList.Columns.Count]; 
                    ListViewItem item = new ListViewItem(number.ToString()); 
                    item.SubItems.AddRange(new string[] { Path.GetFileName(fileName.FullName), media.GetMusicLengthString() }); 
                    item.Tag = fileName.FullName; 
                    lvMusicList.Items.Add(item); 
                    XmlElement xe1 = xmlDoc.CreateElement("name");//创建一个节点 
                    xe1.SetAttribute("genre", Path.GetFileName(fileName.FullName));//设置该节点genre属性 
                    xe1.SetAttribute("filename", fileName.FullName);//设置该节点filename属性 
                    xe1.SetAttribute("lenght", media.GetMusicLengthString());//设置该节点lenght属性 
                    number++; 
                    root.AppendChild(xe1);//添加到节点中       
                    number++; 
                } 
                Application.DoEvents(); 
            } 
            xmlDoc.Save(path + "\\PlayList\\MusicFile.xml"); 
        } 

        /// 
        /// 上一曲 
        /// 
        /// 
        /// 
        private void btnPre_Click(object sender, EventArgs e) 
        { 
            try 
            { 
                //还原当前曲目播放状态 
                lvMusicList.Items[changeValue].SubItems[0].Text = changeItemText; 
                if (changeValue <= 0) 
                    changeValue = lvMusicList.Items.Count - 1; 
                else 
                    changeValue--; 
                //初始化播放曲目 
                GetDownOrUp(sender, e); 
                //按钮状态 
                GetPlayButton(); 
            } 
            catch (Exception exp) 
            { 
                MessageBox.Show(exp.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Error); 
            } 
        } 

        /// 
        /// 下一曲 
        /// 
        /// 
        /// 
        private void btnLast_Click(object sender, EventArgs e) 
        { 
            try 
            { 
                //还原当前曲目播放状态 
                lvMusicList.Items[changeValue].SubItems[0].Text = changeItemText; 
                if (changeValue >= lvMusicList.Items.Count - 1) 
                    changeValue = 0; 
                else 
                    changeValue++; 
                //初始化播放曲目 
                GetDownOrUp(sender, e); 
                //按钮状态 
                GetPlayButton(); 
            } 
            catch (Exception exp) 
            { 
                MessageBox.Show(exp.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Error); 
            } 
        } 

        /// 
        /// 播放暂停 
        /// 
        /// 
        /// 
        private void btnPlayOrPause_Click(object sender, EventArgs e) 
        { 
            try 
            { 
                if (lvMusicList.SelectedItems.Count > 0) 
                { 
                    if (btnPlayOrPause.Text.Equals("开始播放")) 
                    { 
                        media.PlayMusic(); 
                        //设置当前音量 
                        slider1_Scroll(sender, e); 
                        GetPlayButton(); 
                    } 
                    else 
                    { 
                        GetPauseButton(); 
                        media.PauseMusic(); 
                    } 
                } 
                else 
                    MessageBox.Show("请选中要播放的文件", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
            } 
            catch (Exception exp) 
            { 
                MessageBox.Show(exp.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Error); 
            } 
        } 

        /// 
        /// 停止播放 
        /// 
        /// 
        /// 
        private void btnStop_Click(object sender, EventArgs e) 
        { 
            try 
            { 
                //停止播放 
                media.CloseMusic(); 
                //设置控件状态 
                GetStopButton(); 
            } 
            catch (Exception exp) 
            { 
                MessageBox.Show(exp.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Error); 
            } 
        } 

        /// 
        /// 设置进度 
        /// 
        /// 
        /// 
        private void timer1_Tick(object sender, EventArgs e) 
        { 
            try 
            { 
                //设置音乐当前时间 
                progressBarX1.Value = media.GetMusicPos(); 
                //设置音乐的当前进度 
                lblDuration.Text = media.GetMusicPosString(); 
                progressBarX1.Text = (progressBarX1.Value / progressBarX1.Maximum).ToString(); 
                //判断是否已经播放完成 
                if (progressBarX1.Value == progressBarX1.Maximum) 
                { 
                    //还原播放标识编号 
                    lvMusicList.Items[changeValue].SubItems[0].Text = changeItemText; 
                    //播放下一曲 
                    if (changeValue >= lvMusicList.Items.Count - 1) 
                        changeValue = 0; 
                    else 
                        changeValue++; 
                    media.PlayMusic(); 
                    GetDownOrUp(sender, e); 
                } 
            } 
            catch (Exception exp) 
            { 
                MessageBox.Show(exp.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Error); 
            } 

            SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle.ToInt32(), -1, -1); 
        } 

        /// 
        /// 设置音量 
        /// 
        /// 
        /// 
        private void slider1_Scroll(object sender, EventArgs e) 
        { 
            media.SetValume(slider1.Value); 
            //lblSoundValue.Text = "音量:" + slider1.Value.ToString() + "Kbps"; 
        } 

        /// 
        /// 设置声道 
        /// 
        /// 
        /// 
        private void rdo_CheckedChanged(object sender, EventArgs e) 
        { 
            //if (rdoCenter.Checked == true) 
            //    media.SetAudioSource(Media.AudioSource.H); 
            //else if (rdoLeft.Checked == true) 
            //    media.SetAudioSource(Media.AudioSource.L); 
            //else if (rdoRight.Checked == true) 
            //    media.SetAudioSource(Media.AudioSource.R); 
        } 

        /// 
        /// 设置静音 
        /// 
        /// 
        /// 
        private void chkAudioOnOff_CheckedChanged(object sender, EventArgs e) 
        { 
            if (chkAudioOnOff.Checked) 
                media.SetAudioOnOff(true); 
            else 
                media.SetAudioOnOff(false); 
        } 

        /// 
        /// 双击音乐文件列表播放 
        /// 
        /// 
        /// 
        private void lvMusicList_MouseDoubleClick(object sender, MouseEventArgs e) 
        { 
            try 
            { 
                lvMusicList.Items[changeValue].SubItems[0].Text = changeItemText; 
                changeValue = lvMusicList.SelectedIndices[0]; 
                lblMusicName.Text = lvMusicList.SelectedItems[0].SubItems[2].Text; 
                GetDownOrUp(sender, e); 
                GetPlayButton(); 
                media.PlayMusic(); 
                //设置声音 
                media.SetValume(slider1.Value); 
            } 
            catch (Exception exp) 
            { 
                MessageBox.Show(exp.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Error); 
            } 
        } 

        /// 
        /// 删除选中歌曲 
        /// 
        /// 
        /// 
        private void tsmiDeleteChangeMusic_Click(object sender, EventArgs e) 
        { 
            XmlDocument xmlDoc = new XmlDocument(); 
            //获取当前应用程序路径 
            string path = Process.GetCurrentProcess().MainModule.FileName.Substring(0, Process.GetCurrentProcess().MainModule.FileName.LastIndexOf("\\")); 
            //加载Xml文件 
            xmlDoc.Load(path + "\\PlayList\\MusicFile.xml"); 
            XmlNodeList root = xmlDoc.SelectSingleNode("musiclist").ChildNodes;//查找 
            foreach (XmlNode xn in root) 
            { 
                XmlElement xe = (XmlElement)xn; 
                if (xe.GetAttribute("genre") == lvMusicList.SelectedItems[0].SubItems[0].Name) 
                { 
                    xe.RemoveAll();//删除该节点的全部内容 
                } 
            } 
            xmlDoc.Save(path + "\\PlayList\\MusicFile.xml"); 
            //清空列表 
            lvMusicList.Items.Clear(); 
        } 

        /// 
        /// 清空当前列表 
        /// 
        /// 
        /// 
        private void tsmiClearList_Click(object sender, EventArgs e) 
        { 
            XmlDocument xmlDoc = new XmlDocument(); 
            //获取当前应用程序路径 
            string path = Process.GetCurrentProcess().MainModule.FileName.Substring(0, Process.GetCurrentProcess().MainModule.FileName.LastIndexOf("\\")); 
            //加载Xml文件 
            xmlDoc.Load(path + "\\PlayList\\MusicFile.xml"); 
            XmlNode root = xmlDoc.SelectSingleNode("musiclist");//查找 
            root.RemoveAll(); 
            xmlDoc.Save(path + "\\PlayList\\MusicFile.xml"); 
            //清空列表 
            lvMusicList.Items.Clear(); 
        } 

        /// 
        /// 初始化播放曲目 
        /// 
        private void GetDownOrUp(object sender, EventArgs e) 
        { 
            //将当前播放曲目序号保存 
            changeItemText = lvMusicList.Items[changeValue].SubItems[0].Text; 
            //将当前播放曲目标识为正在播放 
            lvMusicList.Items[changeValue].SubItems[0].Text = "★"; 
            //设置当前播放曲目地址 
            media.OpenMusic(lvMusicList.Items[changeValue].Tag.ToString(), this.Handle); 
            //设置曲目总长度 
            lblCurrentPosition.Text = media.GetMusicLengthString(); 
            //开始播放 
            media.PlayMusic(); 
            //设置进度条长度 
            progressBarX1.Maximum = media.GetMusicLength(); 
            //设置曲目标题 
            lblMusicName.Text = lvMusicList.Items[changeValue].SubItems[1].Text; 
            //设置当前音量 
            slider1_Scroll(sender, e); 
        } 

        /// 
        /// 播放状态下控件 
        /// 
        private void GetPlayButton() 
        { 
            btnPlayOrPause.Text = "暂停播放"; 
            btnPre.Enabled = true; 
            btnLast.Enabled = true; 
            btnPlayOrPause.Enabled = true; 
            btnStop.Enabled = true; 
            timer1.Enabled = true; 
        } 

        /// 
        /// 暂停状态下的控件 
        /// 
        private void GetPauseButton() 
        { 
            btnPlayOrPause.Text = "开始播放"; 
            timer1.Enabled = false; 
            btnStop.Enabled = false; 
            btnPlayOrPause.Enabled = true; 
        } 

        /// 
        /// 停止状态下的控件 
        /// 
        private void GetStopButton() 
        { 
            timer1.Enabled = false; 
            btnStop.Enabled = false; 
            btnPlayOrPause.Enabled = false; 
            btnLast.Enabled = false; 
            btnPre.Enabled = false; 
            //将当前播放曲目标识为正在播放 
            lvMusicList.Items[changeValue].SubItems[0].Text = changeItemText; 
            progressBarX1.Value = 0; 
            lblDuration.Text = "00:00:00"; 
            lblCurrentPosition.Text = "00:00:00"; 
            lblMusicName.Text = "暂无音乐文件"; 
        } 

        /// 
        /// 淡出加载主窗体 
        /// 
        /// 
        /// 
        private void tmrShow_Tick(object sender, EventArgs e) 
        { 
            this.Opacity += 0.1; 
            if (this.Opacity >= 1) 
            { 
                this.tmrShow.Dispose(); 
            } 
        } 

        /// 
        /// 窗体状态改变时 
        /// 
        /// 
        /// 
        public void Frm_Resize(object sender, EventArgs e) 
        { 
            //最小化隐藏 
            if (this.WindowState == FormWindowState.Minimized) 
            { 
                this.Visible = false; 
                notifyIcon1.Visible = true; 
            } 
            else 
            { 
                this.Visible = true; 
                notifyIcon1.Visible = false; 
            } 
        } 

        /// 
        /// 双击状态栏图标还原窗体 
        /// 
        /// 
        /// 
        private void notifyIcon1_DoubleClick(object sender, EventArgs e) 
        { 
            this.Visible = true; 
            this.WindowState = FormWindowState.Normal; 

        } 

        /// 
        /// 退出应用程序 
        /// 
        /// 
        /// 
        //private void Frm_FormClosing(object sender, FormClosingEventArgs e) 
        //{ 
        //    //ExitForm exitForm = new ExitForm(); 
        //     exitForm.ShowDialog(this);
        //    e.Cancel = true;
           
        //} 

        /// 
        /// 鼠标按下记录当前位置 
        /// 
        /// 
        /// 
        private void pnlTop_MouseDown(object sender, MouseEventArgs e) 
        { 
            if (e.Button == MouseButtons.Left) 
            { 
                startX = e.X; 
                StartY = e.Y; 
            } 
        } 

        /// 
        /// 鼠标移动时改变窗体位置 
        /// 
        /// 
        /// 
        private void pnlTop_MouseMove(object sender, MouseEventArgs e) 
        { 
            if (e.Button == MouseButtons.Left) 
            { 
                this.Left += e.X - startX; 
                this.Top += e.Y - StartY; 
            } 
        } 

        /// 
        /// 关闭窗体 
        /// 
        /// 
        /// 
        private void lblExit_Click(object sender, EventArgs e) 
        { 
            this.Close(); 
        } 

        /// 
        /// 最小化窗体 
        /// 
        /// 
        /// 
        private void lblMin_Click(object sender, EventArgs e) 
        { 
            this.WindowState = FormWindowState.Minimized; 
        }

        private void tsmiOpenUrlMusic_Click(object sender, EventArgs e)
        {

        } 
    } 
}